package com.bk.cyxf.lf;

import java.sql.Connection;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jt.classic.system.ISystem;
import jt.classic.system.SimpleAction;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.object.IObject;
import jt.classic.system.object.ObjectLCManager;
import jt.classic.system.object.ObjectManager;
import jt.classic.system.user.IUser;

import org.apache.commons.fileupload.FileItem;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.limp.basework.SimpleBean4Table;
import org.limp.basework.Table;
import org.limp.basework.impl.CommonBean4HSQ;
import org.limp.basework.impl.SimpleBean4TableImpl;
import org.limp.basework.tools.BaseworkUtil;
import org.limp.mine.DataTrimmerI;
import org.limp.mine.DateTrimmer;
import org.limp.mine.StringTool;
import org.limp.mine.annex.AnnexItem;

import com.bk.cyxf.log.LogManager;


/**
 * 来访办理
 *
 * @author lvt
 *
 */
public class QtfblAction extends SimpleAction {

    /**
     * 来访办理
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward edithdl(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        ActionForward forward = null;

        Connection conn = null;

        String id = StringTool.checkString(request.getParameter("id"));

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            ObjectLCManager manager = new ObjectLCManager(conn);

            IObject object = manager.getObjectById(id);

            if (object.iobject() == null) {
                request.setAttribute("error", "接访登记信息并不存在");

                forward = mapping.findForward("error");
            } else {
                request.setAttribute("object", object);
                request.setAttribute("wobject", object.iobject());
                forward = mapping.findForward("qtfhdl");
            }
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
            forward = mapping.findForward("error");
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return forward;
    }

    /**
     * 接访科室办理
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward handle(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        ActionForward forward = null;

        Connection conn = null;

        
        CommonBean4HSQ cbh = new CommonBean4HSQ(request);
        Map param = cbh.getResource();
        String id = (String)param.get("id");
        //String backInfo = StringTool.checkString(request.getParameter("H_BACKINFO"));
        String backInfo = (String)param.get("H_BACKINFO");
        //FileItem item = annexItem.getFileItem("HFFJ");

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            ObjectManager manager = new ObjectManager(conn);

            ObjectLCManager lcmanager = new ObjectLCManager(conn);

            IObject object = lcmanager.getObjectById(id);

            if (object.iobject() == null) {
                request.setAttribute("result",
                    "{success: false, errCode : '-1'}");
            } else {
                IUser user = ISystem.getSessionUser(request);

                if (manager.purview(id, user) < 2) {
                    request.setAttribute("result",
                        "{success: false, errCode : '-2'}");
                } else {
                    Table tbl = object.iobject().itable("APP_QTF");

                    Map info = (Map) ((List) object.icontent(tbl)).get(0);

                    String lfid = StringTool.checkString(info.get("QTFID"));
                    //案件接访单位既录入部门
                    String jfdwid = StringTool.checkString(info.get("JFDWID")); 
                    //是否需要各部门均回复
                    String sfxyhf = StringTool.checkString(info.get("XFXYHF")); 
                    DataTrimmerI trimmer = new DataTrimmerI(conn);
                    
                    String sql = "SELECT HID FROM APP_XFHANDLER WHERE XFID = ? AND XF_TYPE = ? AND H_GROUPID = ?";
                    DataTrimmerI.DataItemList dil = trimmer.createDIL();

                    dil.set(lfid);
                    dil.set(2);
                    dil.set(user.igroup().id());

                    Map hdlMap = trimmer.searchSingleData(sql, dil);

                    String hdlkey = StringTool.checkString(hdlMap.get("HID"));

                    SimpleBean4Table sbt = new SimpleBean4TableImpl(
                            "APP_XFHANDLER", cbh);

                    sbt.getResource().put("H_STATUS", "1");
                    sbt.getResource().put("H_BACKINFO", backInfo);
                    sbt.getResource().put("H_DATE", DateTrimmer.getYMDHMS());
                    sbt.getResource().put("HID", hdlkey);
                    sbt.getResource().put("H_USERID", user.id());
                    sbt.getResource().put("H_USERNAME", user.iname());

                    BaseworkUtil util = new BaseworkUtil();
                    
                    /*if("1".equals(sfxyhf)&& jfdwid.equals(user.igroup().id())){

                     	//判断派遣办理的科室是否办理完成
                         String sql_2 = "SELECT * FROM APP_XFHANDLER WHERE XFID = ? AND XF_TYPE = ? AND H_GROUPID != ?";
                         DataTrimmerI.DataItemList dil_2 = trimmer.createDIL();
                         dil_2.set(lfid);
                         dil_2.set("2");
                         dil_2.set(user.igroup().id());	
                         List<Map> handlerList = trimmer.searchMultiData(sql_2, dil_2);
                         boolean handlerResult = true;
                         for(Map m: handlerList){
                         	String h_status = StringTool.checkString(m.get("H_STATUS"));
                         	if("0".equals(h_status)){
                         		//只要有一个科室为办理完成则该条接访记录的科室办理环节未完成
                         		handlerResult = false;
                         		break;
                         	}
                         }
                         
                         //其他科室都办理完成并且当前用户所在科室与派遣人科室一致，由该科室结束办理
                         if(handlerResult){
                         	util.manualUpdate1(sbt, conn);
                            request.setAttribute("result", "{success: true}");
                         }else{
                         	//返回错误信息
                         	request.setAttribute("result", "{success: false,msg:\"协调部门办理意见未填写完成\"}");
                         }
                    	
                    }*/
                    
                    if(jfdwid.equals(user.igroup().id())){

                     	
                         
                         //其他科室都办理完成并且当前用户所在科室与派遣人科室一致，由该科室结束办理
                         
                     	util.manualUpdate1(sbt, conn);
                     	SimpleBean4Table sb = new SimpleBean4TableImpl("APP_QTF");

                        sb.getResource().put("XFXYHF", "1");

                        sb.getResource().put("qtfid", lfid);
                        util.manualUpdate1(sb, conn);
                        request.setAttribute("result", "{success: true}");
                         
                    	
                    }else{
                    	util.manualUpdate1(sbt, conn);
                    	request.setAttribute("result", "{success: true}");
                    	
                    }
                    
                    LogManager lm = new LogManager(conn);
                    lm.log(user, lfid, "2", "qtfhandle", "填写处理意见");

                    

                    

                    conn.commit();

                    
                
                }
            }

            forward = mapping.findForward("result");
        } catch (Exception ex) {
            conn.rollback();

            request.setAttribute("result", "{success: false, errCode : '-4'}");
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return forward;
    }

}
